package com.tubeonfire.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.blobstore.BlobKeyProcess;
import com.tubeonfire.entity.Tube;
import com.tubeonfire.model.admin.PlaylistModel;

public class TubeValidate {

	private static final Logger log = Logger.getLogger(TubeValidate.class
			.getName());

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean checkForm(HttpServletRequest req,
			HttpServletResponse resp, HttpSession session, String action,
			Tube tube) {
		try {
			TreeMap check = new TreeMap();
			String playlist = (String) req.getParameter("playlist");
			String title = (String) req.getParameter("title");
			String description = (String) req.getParameter("description");
			String imgKey = BlobKeyProcess.getBlobKey(req, "img");
			String tags = (String) req.getParameter("tags");
			if (PlaylistModel.byId(playlist, true) == null) {
				check.put("playlist", "Playlist's required !");
			} else {
				tube.setPlaylistId(playlist);
			}
			if (title == null || title.isEmpty()) {
				check.put("title", "Title's required !");
			} else {
				tube.setTitle(title);
				tube.setAlias(StringHelper.getAliasByLanguage(tube.getTitle()));
			}
			if (description == null || description.isEmpty()) {
				check.put("description", "Description's required !");
			} else {
				tube.setDescription(description);
			}
			if (imgKey != null && !imgKey.isEmpty()) {
				tube.setImageUrl(imgKey);
			}
			List<String> listTag = new ArrayList<String>();
			if (tags != null && tags.length() > 0) {
				try {
					String[] tagArray = tags.split(",");
					for (String string : tagArray) {
						listTag.add(string.trim());
					}
					tube.setTags(listTag);
				} catch (Exception e) {

				}
			}
			tube.setOtherTags(TagHelper.getOtherTag(listTag));

			if (check.size() > 0) {
				session.setAttribute("return", true);
				session.setAttribute("check", check);
				session.setAttribute("error",
						"Please fix errors below to finish action !");
				session.setAttribute("obj", tube);
				resp.sendRedirect("/admin/tube/edit?id=" + tube.getId());
				return false;
			} else {
				return true;
			}
		} catch (IOException e) {
			log.warning(e.toString());
			e.printStackTrace();
			return false;
		}
	}
}
